package net.getbang.admin.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import net.getbang.admin.entity.SysUserToken;
import net.getbang.admin.mapper.SysUserTokenMapper;
import net.getbang.admin.service.SysUserTokenService;
import net.getbang.common.redis.SysUserTokenRedis;
import net.getbang.common.shiro.TokenGenerator;

@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken>
		implements SysUserTokenService {

	@Autowired
	private SysUserTokenMapper sysUserTokenMapper;
	
	@Autowired
	private SysUserTokenRedis sysUserTokenRedis;
	// 24小时后过期
	private final static int EXPIRE = 86400;

	@Override
	public SysUserToken queryByToken(String token) {

		SysUserToken sysUserToken = new SysUserToken();

		sysUserToken.setToken(token);

		sysUserToken = sysUserTokenMapper.selectOne(sysUserToken);

		return sysUserToken;
	}
	@Transactional
	public void update(SysUserToken token){
		sysUserTokenRedis.delete(token);
		sysUserTokenMapper.updateById(token);
	}
	@Override
	public Map<String, Object> createToken(Long userId) {
		// 生成一个token
		String token = TokenGenerator.generateValue();

		// 当前时间
		Date now = new Date();
		// 过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
		SysUserToken tokenEntity2 =new SysUserToken();
		tokenEntity2.setUserId(userId);
		// 判断是否生成过token
		SysUserToken tokenEntity = sysUserTokenMapper.selectOne(tokenEntity2);
		if (tokenEntity == null) {
			tokenEntity = new SysUserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			// 保存token
			sysUserTokenMapper.insert(tokenEntity);
		} else {
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			// 更新token
			update(tokenEntity);
		}

		Map<String, Object> result = new HashMap<>();
		result.put("token", token);
		result.put("expire", EXPIRE);
		return result;
	}

	@Override
	public void logout(Long userId) {
		//生成一个token
				String token = TokenGenerator.generateValue();

				//修改token
				SysUserToken tokenEntity = new SysUserToken();
				tokenEntity.setUserId(userId);
				tokenEntity.setToken(token);
				update(tokenEntity);
		
	}

}
